↜ Back to index Introduction to Numerical Analysis 2

Fortran quirks aka The Magic of Fortran

A random list of weird Fortran behavior. Fortran is a very old programming language that preserved backward compatibility and therefore there is a lot of “strange” behavior to be discovered. Mostly with printing to the screen…

IO

Output of real numbers can be surprising.

print *, 0.1
end

prints

  0.100000001

Printing to the screen without entering new line is difficult.

! Illustrates printing to the same line using multiple write commands.
implicit none

! two lines :| (with spaces at the beginning...)
print*, 'Hello'
print*, 'world'

! the same
write(*,*) 'Hello'
write(*,*) 'world'

! this is how it's done
write(*,'(A)',advance='no') 'Hello'
print*,'world'
end

outputs

 Hello
 world
 Hello
 world
Hello world

Note that explicit formatting string must be provided and only write can be used to disable the new line.


Lines of output always have a space at the beginning.

implicit none

print*,'<-- what is this?'
write(*,*) '<-- what is this?'
write(*,'(A)') '<-- No space!'
end

outputs

 <-- what is this?
 <-- what is this?
<-- No space!

IO cannot be “nested”.

Example

print *, f()

contains
    function f()
        print *, 'hi from f'
        f = 0
    end
end

hangs because print on the first line is “active” when f is called and its print is executed, and apparently Fortran does not have a stack for console output.

To solve this, we need to save the return value of f() in a temporary.

x = f()
print *, x